package PUBSUB_TWO.pubsubJmsTemplate;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.connection.CachingConnectionFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.listener.DefaultMessageListenerContainer;

import javax.jms.ConnectionFactory;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.Topic;

@Configuration
public class ConfigClass {
    public static String BROKER_URL = "tcp://0.0.0.0:61616";
    public static String USER = "admin";
    public static String PASSWORD = "admin";
    public static String DESITNATION = "SystemA.SystemB.Topic";

    @Bean
    public ConnectionFactory connectionFactory(){
        //连接池创建Factory
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setTargetConnectionFactory(activeMQConnectionFactory());
        connectionFactory.setSessionCacheSize(20);
        return  connectionFactory;
    }

    private ActiveMQConnectionFactory activeMQConnectionFactory(){
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory();
        activeMQConnectionFactory.setBrokerURL(BROKER_URL);
        activeMQConnectionFactory.setUserName(USER);
        activeMQConnectionFactory.setPassword(PASSWORD);
        return activeMQConnectionFactory;
    }

    @Bean
    public Topic mqTopic(){
        return  new ActiveMQTopic(DESITNATION);
    }

    @Bean
    public MyListenner myMessageListener() {
        return new MyListenner();
    }

    @Bean
    public JmsTemplate mqJmsTemplate(ConnectionFactory factory,Topic Topic){
        JmsTemplate jmsTemplate = new JmsTemplate();
        jmsTemplate.setConnectionFactory(factory);
        jmsTemplate.setDefaultDestination(Topic);
        return jmsTemplate;
    }

    @Bean
    public DefaultMessageListenerContainer messageListenerContainer(ConnectionFactory factory, Topic priceTopic, MessageListener messageListener) {
        DefaultMessageListenerContainer mlc = new DefaultMessageListenerContainer();
        mlc.setConnectionFactory(factory);
        mlc.setDestination(priceTopic);
        mlc.setMessageListener(messageListener);

        return mlc;
    }
}
